package com.liuyang.concurrency.chapter9;

import java.util.*;

public class CaptureService {


    private static LinkedList<Control> CONTROLLER = new LinkedList<>();

    private static final int MAX_WORKER = 5;

    public static void main(String[] args) {
        List<Thread> worker = new ArrayList<>();
        Arrays.asList("M1","M2","M3","M4","M5","M6","M7","M8","M9","M10").stream()
                .map(CaptureService::createCaptureThread)
                .forEach(thread -> {
                    thread.start();
                    worker.add(thread);
                });
        worker.stream().forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Optional.of("All of capture work finished").ifPresent(System.out::println);
    }

    private static Thread createCaptureThread(String name){
        return new Thread(() ->{
            Optional.of("The woker ["+Thread.currentThread().getName()+"] begin capture data.....").ifPresent(System.out::println);;
            synchronized (CONTROLLER){
                while (CONTROLLER.size() > MAX_WORKER){
                    try {
                        CONTROLLER.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                CONTROLLER.addLast(new Control());
            }
            Optional.of("The worker ["+Thread.currentThread().getName()+"] is working....").ifPresent(System.out::println);;
            try {
                Thread.sleep(10_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (CONTROLLER){
                Optional.of("The worker ["+Thread.currentThread().getName()+"] END capture data").ifPresent(System.out::println);;
                CONTROLLER.removeFirst();
                CONTROLLER.notifyAll();

            }


        },name);
    }
}

class Control{

}
